from selenium import webdriver

driver = webdriver.Chrome()

driver.get('http://cdn1.python3.vip/files/selenium/sample3.html')

link = driver.find_element_by_css_selector('a[href*="www.bing.com"]')

link.click()

# 保存当前窗口句柄
local = driver.current_window_handle

# 遍历每个窗口句柄
for hadle in driver.window_handles:
    # 进入该窗口
    driver.switch_to.window(hadle)

    if 'Bing' in driver.title:
        break
# 确认是否在新窗口，打印新窗口网页title
print(driver.title)

driver.find_element_by_id('sb_form_q').send_keys('新月')
# 提交搜索的关键字
win = driver.find_element_by_id('sb_form_go')
win.click()
# 进入百度百科
driver.find_element_by_css_selector('a[href*="baike.baidu.com"]').click()
# 打印当前窗口网页的title
print(driver.title)
# 回到最开始的初始窗口
driver.switch_to.window(local)